<?php
namespace App\Event;

/**
 * SWOOLE 启动之前
 * consul 服务自动注册
 */
use App\Consul\ConsulServices;
use Hyperf\Utils\ApplicationContext;
use App\Service\AppService\SystemCacheConfigService;

class ConsulServerStartCallback
{
    protected $server_ip;
    protected $server_port;
    protected $consul_ip;
    protected $consul_port;
    protected $consul_status;
    protected $consul_type;
    protected $consul_url;
    protected $app_name;
    public function __construct()
    {
        if( ! $this->consul_status ) {
            return false;
        }
        
        $redis = new \Redis();
        $redisConfig = config('redis.default');
        $redis->connect($redisConfig['host'],(int)$redisConfig['port']);
        $redis->auth($redisConfig['auth']);
        $redis->select(SystemCacheConfigService::SYSTEM_CACHE_CONFIG_RDB);
        $config     = $redis->get(SystemCacheConfigService::SYSTEM_CACHE_CONFIG_SERVICE_KEY.'consul');
        $config     = @json_decode($config,true);
        $baseurl    = parse_url($config['baseurl']);
        $this->server_ip      = $config['local_host'];
        $this->server_port    = (int)$config['local_port'];
        $this->consul_ip      = $baseurl['host'];
        $this->consul_port    = (int)$baseurl['port'];
        $this->consul_status  = $config['is_local'];
        $this->consul_type    = env('CONSUL_TYPE');
        $this->app_name       = env('APP_NAME');
        $this->consul_url     = "http://{$this->consul_ip}:{$this->consul_port}";
    }
    
    /**
     * 启动开始注册服务
     */
    public function beforeStart()
    {
        if( ! $this->consul_status ) {
            return false;
        }
        
        if( $this->consul_type == 'kv' ) {
            return $this->startAutoRegisterConsulKvService();
        } elseif ( $this->consul_type == 'agent' ) {
            return $this->startAutoRegisterConsulAgentService();
        } else {
            return false;
        }
    }
    
    /**
     * 服务注册、发现、健康心跳检查、需要配合网关使用（openresty）等
     */
    public function startAutoRegisterConsulAgentService()
    {
        $server_id = $this->server_ip.'_'.$this->server_port;
        $app_name  = 'RpcTcpServices';
        $registerService = [
            "ID"     => $server_id,
            "Name"   => $app_name,
            "Tags"   => ["dev"],
            "Address"=> $this->server_ip,
            "Port"   => (int)$this->server_port,
            "Check"  => [
                "name"      => "rpc tcp server",
                "tcp"       => $this->server_ip . ":" . $this->server_port ,
                //"name"      => "HTTP API on port {$this->server_port}",
                //"http"      => "http://{$this->server_ip}:{$this->server_port}/health",
                "interval"  => "10s",
                "timeout"   => "30s"
            ]
        ];
        
        //获取可用的服务
        $container = ApplicationContext::getContainer();
        $consul = $container->get(ConsulServices::class);
        $consul->consul_url= $this->consul_url;
        /* $consul->getService($app_name);
        $consul->servers[$app_name]; */
        return $consul->registerService($registerService);
    }    
    
    /**
     * Kv nginx + upsyc consul 动态负载均衡算法(启动脚本自动加入nginx 动态负载均衡配置文件)
     */
    public function startAutoRegisterConsulKvService()
    {
        $container = ApplicationContext::getContainer();
        $consul = $container->get(ConsulServices::class);
        $consul->consul_url= $this->consul_url;
        $value = [
            'weight'        => 1,
            'max_fails'     => 3,
            'fail_timeout'  => 10,
            'down'          => 0,
            'max_conns'     => 1024
        ];
        $key = "upstreams/{$this->app_name}/{$this->server_ip}:{$this->server_port}";
        //$consul->delKv($key);
        return $consul->putKv($key,$value);
    }
}